package com.mm.controller.note;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mm.base.exception.NoteException;
import com.mm.domain.note.DNote;
import com.mm.domain.note.DNoteExcel;
import com.mm.domain.note.WangEditor;
import com.mm.domain.quartz.ExcelTitleAlias;
import com.mm.serivce.note.DNoteService;
import com.mm.util.note.ExcelExImUtil;
import com.mm.util.result.DPage;
import com.mm.util.result.DResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 描述: 笔记
 *
 * @author: yanglin
 * @Date: 2021-05-12-11:29
 * @Version: 1.0
 */
@Api(value = "/note/v1/", tags = {"描述: 笔记"})
@Slf4j
@RestController
@RequestMapping("/note/v1/")
public class NoteController {
    private final DNoteService noteService;

    public NoteController(DNoteService noteService) {
        this.noteService = noteService;
    }

    /**
     * 笔记列表
     *
     * @param map
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "Map<String, Object>", dataTypeClass = Map.class, name = "map", value = "", required = true)
    })
    @ApiOperation(value = "笔记列表", notes = "笔记列表", httpMethod = "POST")
    @PostMapping("query")
    public DResult queryMyNotes(@RequestBody Map<String, Object> map) {
        Integer page = Integer.parseInt(map.get("page").toString());
        Integer limit = Integer.parseInt(map.get("limit").toString());
        String text = map.get("text").toString();
        long startTime = Long.parseLong(map.get("startTime").toString());
        if (startTime <= 0) {
            // 获取当日零点的毫秒数（我们是正八区）
            startTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        }
        long endTime = Long.parseLong(map.get("endTime").toString());
        if (endTime <= 0) {
            // 获取当日24点的毫秒数（我们是正八区）
            endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        }
        Page<DNote> page1 = noteService.queryMyNoteList(page, limit, text, startTime, endTime);
        DPage<DNote> page2 = DPage.to(page1);
        return DResult.of(page2);
    }

    /**
     * 笔记编辑
     *
     * @param note
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "DNote", dataTypeClass = DNote.class, name = "DNote", value = "", required = true)
    })
    @ApiOperation(value = "笔记编辑", notes = "笔记编辑", httpMethod = "POST")
    @Transactional
    @PostMapping("saveOrUpdate")
    public DResult saveOrUpdate(@RequestBody DNote note) {
        boolean flag = false;
        if (note.getNId() < 0) {
            // 新增
            flag = noteService.save(note);
        } else if (note.getNId() > 0) {
            // 更新
            flag = noteService.updateById(note);
        } else {
            throw new NoteException("N0004", "笔记ID为空");

        }
        return DResult.of(flag);
    }

    /**
     * 笔记删除
     *
     * @param nId
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", dataTypeClass = Integer.class, name = "nId", value = "", required = true)
    })
    @ApiOperation(value = "笔记删除", notes = "笔记删除", httpMethod = "POST")
    @Transactional
    @PostMapping("remove")
    public DResult remove(@RequestParam Integer nId) {
        boolean flag = false;
        if (nId > 0) {
            flag = noteService.remove(nId);
        } else {
            throw new NoteException("N0004", "笔记ID为空或为负数");

        }
        return DResult.of(flag);
    }

    /**
     * 笔记图片上传
     *
     * @param multipartFile
     * @param request
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "file", dataTypeClass = MultipartFile.class, name = "multipartFile", value = "", required = true)
    })
    @ApiOperation(value = "笔记图片上传", notes = "笔记图片上传", httpMethod = "POST")
    @PostMapping("upload")
    public WangEditor upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        try {
            // 获取项目路径
            String realPath = new File("").getCanonicalPath();
            InputStream inputStream = multipartFile.getInputStream();
            // 根目录下新建文件夹upload，存放上传图片
            String uploadPath = realPath + "/springboot-note/src/main/resources/static/upload";
            // 获取文件名称
            String fileOldName = multipartFile.getOriginalFilename();
            String suffix = fileOldName.substring(fileOldName.length() - 4);
            String filename = DateUtil.today().replaceAll("-", "") + System.currentTimeMillis();
            if (suffix.contains(".")) {
                filename += suffix;
            } else {
                filename += "." + suffix;
            }
            // 将文件上传的服务器根目录下的upload文件夹
            File file = new File(uploadPath, filename);
            FileUtils.copyInputStreamToFile(inputStream, file);
            // 返回图片访问路径
            String url = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + request.getContextPath() + "/upload/" + filename;
            //WangEditor类 是定义成功或者失败的返回格式在第9点
            log.info("uploadUrl, {}", url);
            WangEditor we = new WangEditor(url);
            return we;
        } catch (IOException e) {
        }
        return null;
    }

    /**
     * 月报记录查询
     *
     * @param startTime
     * @param endTime
     * @param response
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", dataTypeClass = String.class, name = "startTime", value = "", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", dataTypeClass = String.class, name = "endTime", value = "", required = true)
    })
    @ApiOperation(value = "月报记录查询", notes = "月报记录查询", httpMethod = "POST")
    @PostMapping("downloadData")
    public DResult queryExportData(@RequestParam String startTime, @RequestParam String endTime, HttpServletResponse response) throws UnsupportedEncodingException {
        DateTime start = DateUtil.parse(startTime, "yyyy-MM-dd");
        DateTime end = DateUtil.parse(endTime, "yyyy-MM-dd");
        List<DNote> DNoteList = noteService.queryMyNote(start, end);
        List<ExcelTitleAlias> tableNames = new ArrayList<>();
        tableNames.add(new ExcelTitleAlias("createTime", "日期"));
        tableNames.add(new ExcelTitleAlias("text", "记录"));
        String fileName = "月报记录-" + DateUtil.format(new Date(), "yyyy-MM-dd") + ".xlsx";
        // fileName = URLEncoder.encode(fileName, "UTF-8");
        DNoteExcel DNoteExcel = new DNoteExcel();
        DNoteExcel.setDNotes(DNoteList);
        DNoteExcel.setTableNames(tableNames);
        DNoteExcel.setFileName(fileName);
        return DResult.of(DNoteExcel);
    }

    /**
     * 月报记录导出
     *
     * @param startTime
     * @param endTime
     * @param response
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", dataTypeClass = String.class, name = "startTime", value = "", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", dataTypeClass = String.class, name = "endTime", value = "", required = true)
    })
    @ApiOperation(value = "月报记录导出", notes = "月报记录导出", httpMethod = "GET")
    @GetMapping("download")
    public void exportData(@RequestParam String startTime, @RequestParam String endTime, HttpServletResponse response) throws UnsupportedEncodingException {
        DateTime start = DateUtil.parse(startTime, "yyyy-MM-dd");
        DateTime end = DateUtil.parse(endTime, "yyyy-MM-dd");
        List<DNote> DNoteList = noteService.queryMyNote(start, end);

        String fileName = "月报记录-" + DateUtil.format(new Date(), "yyyy-MM-dd");
        fileName = URLEncoder.encode(fileName, "UTF-8");

        List<ExcelTitleAlias> excelTitleAlias = new ArrayList<ExcelTitleAlias>();
        excelTitleAlias.add(new ExcelTitleAlias("createTime", "日期"));
        excelTitleAlias.add(new ExcelTitleAlias("text", "记录"));

        ExcelExImUtil.exportExcel(response, fileName, excelTitleAlias, DNoteList);

    }
}
